package servlet.wxpay;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import entity.Order;
import service.OrderService;
import service.impl.OrderServiceImpl;
import servlet.wxpay.sdk.MyConfig;
import servlet.wxpay.sdk.WXPay;
import servlet.wxpay.sdk.WXPayUtil;

public class WxPayNotifyServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private OrderService orderService = new OrderServiceImpl();
       
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		try{
	
			String notifyData = ""; // 支付结果通知的xml格式数据
			
			//1.从request获取XML流，转化成为MAP数据
            InputStream inputStream = request.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
            StringBuffer sb = new StringBuffer();
            String temp;
            while ((temp = reader.readLine()) != null) {
                sb.append(temp);
            }
            reader.close();
            inputStream.close();
            
            notifyData = sb.toString();
	
	        MyConfig config = new MyConfig();
	        WXPay wxpay = new WXPay(config);
	
	        Map<String, String> notifyMap = WXPayUtil.xmlToMap(notifyData);  // 转换成map
	        
	        //对数据进行签名
	        if (wxpay.isResponseSignatureValid(notifyMap)) {
	            // 签名正确
	            // 进行处理。
	            // 注意特殊情况：订单已经退款，但收到了支付结果成功的通知，不应把商户侧订单状态从退款改成支付成功
	        	
	        	String returnCode = notifyMap.get("return_code");

                if (returnCode.equals("SUCCESS")) {
                	if(notifyMap.get("result_code").equals("SUCCESS")){
                		//微信支付订单号
                        String transactionId = notifyMap.get("transaction_id");
                        //商户订单号
                        String outTradeNo = notifyMap.get("out_trade_no");
                        Order order = orderService.findByOrderNO(outTradeNo);
    					if (order!=null && order.getStatus()==0) {
    						order.setPayType(2);
    						order.setStatus(1);
    						order.setTrade_no(transactionId);
    						orderService.updateStatus(order);
    					}
    					System.out.println("微信支付成功");
                	} else {
                		System.out.println("微信支付失败，"+notifyMap.get("err_code")+"---"+notifyMap.get("err_code_des"));
                	}
                	
                } else {
                	System.out.println("微信支付失败，"+notifyMap.get("return_msg"));
                }
                
                response.getWriter().write("<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>");
	        } else {
	            // 签名错误，如果数据里没有sign字段，也认为是签名错误
	        	System.out.println("微信支付异步通知，签名错误");
	        	response.getWriter().write("<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[签名失败]]></return_msg></xml>");
	        }
		} catch (Exception e){
			e.printStackTrace();
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
